package model

import (
	"gowork/customerReplacementProcess/utils"
	"sync"
	"time"
)

type CustomerChange struct {
	Id int64 `xorm:"pk autoincr"`
	CustomerId int64
	Submitter int64
	OrganId int64
	Reason int
	Explain string
	State int
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Customer struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	Type int
	FounderId int64
	FounderName string
	BelongerId int64
	BelongerName string
	AllocationTime time.Time
	CreatedAt time.Time
	UpdatedAt time.Time
}

type NewCustomerDistribution struct {
	Id int64 `xorm:"pk autoincr"`
	CustomerName string
	CustomerId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type LinkageRecord struct {
	Id int64 `xorm:"pk autoincr"`
	CustomerName string
	CustomerId int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Adviser struct {
	Id int64 `xorm:"pk autoincr"`
	Name string
	RoleId int64
	Achievement int64
	CreatedAt time.Time
	UpdatedAt time.Time
}

type Order struct {
	Id int64 `xorm:"pk autoincr"`
	Type int
	State int
	CustomerId int64
	CustomerName string
	NextSinglePersonId int64
	NextSinglePersonName string
	MealList string
	TotalPrice int64
	Region string
	CreatedAt time.Time
	UpdatedAt time.Time
}

//type ServiceAudit struct {
//	Id int64 `xorm:"pk autoincr"`
//	Type int
//	CustomerChangeId int64
//	Reviewer int64
//	ReviewerName string
//	State int
//	Result int
//	CreatedAt time.Time
//	UpdatedAt time.Time
//}
//
//type PinTubeAudit struct {
//	Id int64 `xorm:"pk autoincr"`
//	CustomerChangeId int64
//	Reviewer int64
//	State int
//	Result int
//	CreatedAt time.Time
//	UpdatedAt time.Time
//}
//
//type ConsultantFeedback struct {
//	Id int64 `xorm:"pk autoincr"`
//	CustomerChangeId int64
//	Reviewer int64
//	State int
//	Result int
//	CreatedAt time.Time
//	UpdatedAt time.Time
//}

type Message struct {
	Id int64 `xorm:"pk autoincr"`
	AdviserId int64
	Context string
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (customerChange *CustomerChange)Apply(cc *CustomerChange)(map[string]interface{}, error){

	w := new(utils.Worker)

	cc.Id = w.GetId()
	cc.State = 1
	cc.CreatedAt = time.Now()
	cc.UpdatedAt = time.Now()

	var oList []*Order
	x.Where("customer_id = ?", cc.CustomerId).Find(&oList)

	if len(oList) > 0 {
		return map[string]interface{}{"message": "该客户已下过单，不可更换","code":400}, nil
	}

	var ncd NewCustomerDistribution
	x.Where("customer_id = ?", cc.CustomerId).And("created_at >= ?", time.Now().AddDate(0,0,-35)).Get(&ncd)
	if ncd.Id == 0{
		return map[string]interface{}{"message": "提交时间已超过提交期限，不可提交","code":400}, nil
	}

	var c Customer
	x.Id(cc.CustomerId).Get(&c)
	if c.BelongerId != cc.Submitter{
		return map[string]interface{}{"message": "非自己客户，不可提交","code":400}, nil
	}

	if cc.OrganId != 20200726 && cc.OrganId != 20200727 && cc.OrganId != 20200728{
		return map[string]interface{}{"message": "非新客户派发小组的顾问，不可提交","code":400}, nil
	}

	var ccList []*CustomerChange
	x.Where("customer_id = ?", cc.CustomerId).Find(&ccList)
	if len(ccList) >=2 {
		return map[string]interface{}{"message": "已对该客户提交2次更换，不可再提交","code":400}, nil
	}

	if cc.Reason == 1 || cc.Reason == 2 || cc.Reason == 3 || cc.Reason == 4 || cc.Reason == 5 || cc.Reason == 6{
		var lkrList []*LinkageRecord
		x.Where("customer_id = ?", cc.CustomerId).And("created_at >= ?", time.Now().AddDate(0, 0, -7)).Find(&lkrList)
		if len(lkrList) == 0{
			return map[string]interface{}{"message": "7个工作日内，没有联动记录，不可更换","code":200}, nil
		}else {

			x.Insert(cc)

			var sa = Audit{
				Id:                 w.GetId(),
				CustomerChangeId:   cc.Id,
				State:     1,
				CustomerChangeSatus: 1,
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			}
			x.Insert(&sa)

			return map[string]interface{}{"message": "成功","code":200}, nil
		}
	}

	x.Insert(cc)

	var sa = Audit{
		Id:                 w.GetId(),
		CustomerChangeId:   cc.Id,
		State:     1,
		CustomerChangeSatus: 1,
		CreatedAt: time.Now(),
		UpdatedAt: time.Now(),
	}
	x.Insert(&sa)

	return map[string]interface{}{"message": "成功","code":200}, nil
}

type Audit struct {
	Id int64 `xorm:"pk autoincr"`
	CustomerChangeId int64
	Reviewer int64
	ReviewerName string
	State int
	CustomerChangeSatus int
	CreatedAt time.Time
	UpdatedAt time.Time
}

var clock sync.Mutex

func (customerChange *CustomerChange)Confirmation(aId int64, auditId int64)(map[string]interface{}, error){

	clock.Lock()

	w := new(utils.Worker)

	var adviser Adviser
	x.Id(aId).Get(&adviser)

	var audit Audit
	x.Id(auditId).Get(&audit)
	if audit.State != 1{
		clock.Unlock()

		return map[string]interface{}{"code":400, "message":"该申请已被审核"}, nil
	}

	var cc CustomerChange
	x.Id(audit.CustomerChangeId).Get(&cc)

	var c Customer
	x.Id(cc.CustomerId).Get(&c)

	if audit.CustomerChangeSatus == 1{
		if cc.Reason == 1 || cc.Reason == 2 || cc.Reason == 3 || cc.Reason == 4 {

			var cf = Audit{
				Id:     w.GetId(),
				CustomerChangeId:   audit.CustomerChangeId,
				State:     1,
				CustomerChangeSatus: 2,
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			}
			x.Insert(&cf)

			audit.Reviewer = aId
			audit.ReviewerName = adviser.Name
			audit.State = 2
			x.Id(audit.Id).Update(&audit)

			cc.State = 2
			x.Id(audit.CustomerChangeId).Update(&cc)

			var m = Message{
				Id:     w.GetId(),
				AdviserId: c.FounderId,
				Context: "需要进行反馈",
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			}
			x.Insert(&m)

			clock.Unlock()

			return map[string]interface{}{"code":200, "message":"成功"}, nil
		}else {
			var pta = Audit{
				Id:     w.GetId(),
				CustomerChangeId:   audit.CustomerChangeId,
				State:     1,
				CustomerChangeSatus: 4,
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			}
			x.Insert(&pta)

			audit.Reviewer = aId
			audit.ReviewerName = adviser.Name
			audit.State = 2
			x.Id(audit.Id).Update(&audit)

			cc.State = 4
			x.Id(audit.CustomerChangeId).Update(&cc)

			clock.Unlock()

			return map[string]interface{}{"code":200, "message":"成功"}, nil
		}
	}else if audit.CustomerChangeSatus == 2{
		var cf = Audit{
			Id:     w.GetId(),
			CustomerChangeId:   audit.CustomerChangeId,
			State:     1,
			CustomerChangeSatus: 3,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		x.Insert(&cf)

		audit.Reviewer = aId
		audit.ReviewerName = adviser.Name
		audit.State = 2
		x.Id(audit.Id).Update(&audit)

		cc.State = 3
		x.Id(audit.CustomerChangeId).Update(&cc)

		clock.Unlock()

		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}else if audit.CustomerChangeSatus == 3{
		var pta = Audit{
			Id:     w.GetId(),
			CustomerChangeId:   audit.CustomerChangeId,
			State:     1,
			CustomerChangeSatus: 4,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		x.Insert(&pta)

		audit.Reviewer = aId
		audit.ReviewerName = adviser.Name
		audit.State = 2
		x.Id(audit.Id).Update(&audit)

		cc.State = 4
		x.Id(audit.CustomerChangeId).Update(&cc)

		clock.Unlock()

		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}else if audit.CustomerChangeSatus == 4{
		if cc.Reason == 1 || cc.Reason == 2 || cc.Reason == 3 || cc.Reason == 4 || cc.Reason == 7 || cc.Reason == 8 {
			var o Order
			x.Where("next_single_person_id = ?", c.FounderId).And("customer_id = ?", c.Id).Desc("created_at").Limit(1).Get(&o)

			audit.Reviewer = aId
			audit.ReviewerName = adviser.Name
			audit.State = 2
			x.Id(audit.Id).Update(&audit)

			cc.State = 5
			x.Id(audit.CustomerChangeId).Update(&cc)

			var a Adviser
			x.Id(c.FounderId).Get(&a)
			a.Achievement -= o.TotalPrice
			x.Id(c.FounderId).Update(&a)

			var m = Message{
				Id:     w.GetId(),
				AdviserId: c.FounderId,
				Context:  "扣除业绩",
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
			}
			x.Insert(&m)

			clock.Unlock()

			return map[string]interface{}{"code":200, "message":"成功"}, nil
		}

		audit.Reviewer = aId
		audit.ReviewerName = adviser.Name
		audit.State = 2
		x.Id(audit.Id).Update(&audit)

		cc.State = 5
		x.Id(audit.CustomerChangeId).Update(&cc)

		var m = Message{
			Id:     w.GetId(),
			AdviserId: c.FounderId,
			Context:  "更换",
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		x.Insert(&m)

		clock.Unlock()

		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	clock.Unlock()

	return map[string]interface{}{"code":200, "message":"成功"}, nil
}

var rlock sync.Mutex

func (customerChange *CustomerChange)Replacement(aId int64, auditId int64)(map[string]interface{}, error){

	rlock.Lock()

	w := new(utils.Worker)

	var adviser Adviser
	x.Id(aId).Get(&adviser)

	var audit Audit
	x.Id(auditId).Get(&audit)
	if audit.State != 1{
		rlock.Unlock()

		return map[string]interface{}{"code":200, "message":"该申请已被退回"}, nil
	}

	var cc CustomerChange

	var c Customer
	x.Id(cc.CustomerId).Get(&c)

	if audit.CustomerChangeSatus == 1{

		audit.Reviewer = aId
		audit.ReviewerName = adviser.Name
		audit.State = 3
		x.Id(audit.Id).Update(&audit)

		cc.State = 6
		x.Id(audit.CustomerChangeId).Update(&cc)

		var m = Message{
			Id:     w.GetId(),
			AdviserId: c.BelongerId,
			Context:  "不更换",
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		x.Insert(&m)

		rlock.Unlock()

		return map[string]interface{}{"code":200, "message":"成功"}, nil

	}else if audit.CustomerChangeSatus == 2{
		var pta = Audit{
			Id:     w.GetId(),
			CustomerChangeId:   audit.CustomerChangeId,
			State:     1,
			CustomerChangeSatus: 4,
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		x.Insert(&pta)

		audit.Reviewer = aId
		audit.ReviewerName = adviser.Name
		audit.State = 3
		x.Id(audit.Id).Update(&audit)

		cc.State = 4
		x.Id(audit.CustomerChangeId).Update(&cc)

		rlock.Unlock()

		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}else if audit.CustomerChangeSatus == 3{

		audit.Reviewer = aId
		audit.ReviewerName = adviser.Name
		audit.State = 3
		x.Id(audit.Id).Update(&audit)

		cc.State = 6
		x.Id(audit.CustomerChangeId).Update(&cc)

		var m = Message{
			Id:     w.GetId(),
			AdviserId: c.BelongerId,
			Context:  "不更换",
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		x.Insert(&m)

		rlock.Unlock()

		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}else if audit.CustomerChangeSatus == 4{

		audit.Reviewer = aId
		audit.ReviewerName = adviser.Name
		audit.State = 3
		x.Id(audit.Id).Update(&audit)

		cc.State = 6
		x.Id(audit.CustomerChangeId).Update(&cc)

		var m = Message{
			Id:     w.GetId(),
			AdviserId: c.BelongerId,
			Context:  "不更换",
			CreatedAt: time.Now(),
			UpdatedAt: time.Now(),
		}
		x.Insert(&m)

		rlock.Unlock()

		return map[string]interface{}{"code":200, "message":"成功"}, nil
	}

	rlock.Unlock()

	return map[string]interface{}{"code":200, "message":"成功"}, nil
}

func (customerChange *CustomerChange)QueryAutid(adviserId int64)([]*Audit, error){

	var adviser Adviser
	x.Id(adviserId).Get(&adviser)

	var auditList []*Audit

	if adviser.RoleId == 306209138461900802{
		x.Where("customer_change_satus = ?", 1).Or("customer_change_satus = ?", 3).Find(&auditList)
	}else if adviser.RoleId == 306209138461900800{
		//x.Join("INNER", "audit", "customer_change.id = audit.customer_change_id").
		//	Join("INNER", "customer", "customer.id = customer_change.customer_id").
		//	Where("audit.customer_change_satus = ?", 2).
		//	And("customer.founder_id = ?", adviserId).
		//	Find(&auditList)

		x.SQL("select a.* from audit a inner join customer_change cc on a.customer_change_id = cc.id inner join customer c on c.id = cc.customer_id where a.customer_change_satus = 2 and c.founder_id = ?", adviserId).Find(&auditList)
	}else if adviser.RoleId == 306209138461900803{
		x.Where("customer_change_satus = ?", 4).Find(&auditList)
	}

	return auditList, nil
}

//func ServiceConfirmation(aId int64, saId int64)(map[string]interface{}, error){
//
//	var sa ServiceAudit
//	x.Id(saId).Get(&sa)
//
//	var cc CustomerChange
//
//	sa.Reviewer = aId
//	sa.State = 1
//	sa.Result = 1
//	x.Id(sa.Id).Update(&sa)
//
//	var c Customer
//	x.Id(cc.CustomerId).Get(&c)
//
//	if cc.Reason == 1 || cc.Reason == 2 || cc.Reason == 3 || cc.Reason == 4 {
//
//		cc.State = 2
//		x.Id(sa.CustomerChangeId).Update(&cc)
//
//		var cf = ConsultantFeedback{
//			CustomerChangeId:   sa.CustomerChangeId,
//			State:     1,
//			CreatedAt: time.Now(),
//			UpdatedAt: time.Now(),
//		}
//		x.Insert(&cf)
//
//		var m = Message{
//			AdviserId: c.FounderId,
//			CreatedAt: time.Now(),
//			UpdatedAt: time.Now(),
//		}
//		x.Insert(&m)
//
//		return map[string]interface{}{"code":200, "message":"成功"}, nil
//	}
//
//	cc.State = 3
//	x.Id(sa.CustomerChangeId).Update(&cc)
//
//	var pta = PinTubeAudit{
//		CustomerChangeId: sa.CustomerChangeId,
//		State:            0,
//		CreatedAt: time.Now(),
//		UpdatedAt: time.Now(),
//	}
//	x.Insert(&pta)
//	return map[string]interface{}{"code":200, "message":"成功"}, nil
//}
//
//func Feedback(aId int64, cfId int64, f int)(map[string]interface{}, error){
//
//	var cf ConsultantFeedback
//	x.Id(cfId).Get(&cf)
//
//	cf.State = 1
//	cf.Reviewer = aId
//	cf.Result = f
//	x.Id(cf.Id).Update(&cf)
//
//	var cc CustomerChange
//
//	if f == 1{
//
//		cc.State = 3
//		x.Id(cf.CustomerChangeId).Update(&cc)
//
//		cf.State = 1
//		x.Id(cf.Id).Update(&cf)
//
//		var pta = PinTubeAudit{
//			CustomerChangeId: cf.CustomerChangeId,
//			State:            0,
//			CreatedAt: time.Now(),
//			UpdatedAt: time.Now(),
//		}
//		x.Insert(&pta)
//		return map[string]interface{}{"code":200, "message":"成功"}, nil
//	}else {
//
//		cc.State = 2
//		x.Id(cf.CustomerChangeId).Update(&cc)
//
//		var sa = ServiceAudit{
//			Type:      2,
//			CustomerChangeId:   cf.CustomerChangeId,
//			State:     0,
//			CreatedAt: time.Now(),
//			UpdatedAt: time.Now(),
//		}
//		x.Insert(&sa)
//		return map[string]interface{}{"code":200, "message":"成功"}, nil
//	}
//}
//
//func Replace(aId int64, ptaId int64, r int)(map[string]interface{}, error){
//
//	var pta PinTubeAudit
//	x.Id(ptaId).Get(&pta)
//
//	pta.State = 1
//	pta.Reviewer = aId
//	pta.Result = r
//	x.Id(pta.Id).Update(&pta)
//
//	var cc CustomerChange
//	x.Id(pta.CustomerChangeId).Get(&cc)
//	cc.State = 4
//	x.Id(pta.CustomerChangeId).Update(&cc)
//
//	var c Customer
//	x.Id(cc.CustomerId).Get(&c)
//	if r == 1{
//		if cc.Reason == 1 || cc.Reason == 2 || cc.Reason == 3 || cc.Reason == 4 || cc.Reason == 6 || cc.Reason == 8 {
//			var o Order
//			x.Where("aext_single_person_id = ?", c.FounderId).And("customer_id = ?", c.Id).Desc("created_at").Limit(1).Get(&o)
//
//			var a Adviser
//			a.Achievement -= o.TotalPrice
//			x.Id(c.FounderId).Update(&a)
//		}
//
//		var m = Message{
//			AdviserId: c.FounderId,
//			CreatedAt: time.Now(),
//			UpdatedAt: time.Now(),
//		}
//		x.Insert(&m)
//	}else {
//		var m = Message{
//			AdviserId: c.BelongerId,
//			CreatedAt: time.Now(),
//			UpdatedAt: time.Now(),
//		}
//		x.Insert(&m)
//	}
//
//	return map[string]interface{}{"code":200, "message":"成功"}, nil
//}

































